from grid_env_ideal_obs_repeat_task import *
from grid_agent import *
from checkpoint_utils import *
from maze_factory import *
from replay_config import *
import argparse
import json
import sys
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.lines import Line2D
from sklearn.manifold import TSNE
import random
from sklearn.decomposition import PCA
from matplotlib.animation import FuncAnimation
from sklearn.cluster import KMeans
import threading
import mplcursors
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from scipy.spatial import KDTree
from sklearn.linear_model import LinearRegression
import umap
from ripser import ripser
from persim import plot_diagrams
from scipy.spatial.distance import pdist, squareform


def progress_bar(current, total, barLength = 100):
    percent = float(current) * 100 / total
    arrow = '-' * int(percent/100 * barLength - 1) + '>'
    spaces = ' ' * (barLength - len(arrow))

    print('Progress: [%s%s] %d %%' % (arrow, spaces, percent), end='\r')
    sys.stdout.flush()

@partial(jax.jit, static_argnums=(3,))
def model_forward(variables, state, x, model):
    """ forward pass of the model
    """
    return model.apply(variables, state, x)

@jit
def get_action(y):
    return jnp.argmax(y)
get_action_vmap = jax.vmap(get_action)

# load landscape and states from file
def load_task(pth = "./logs/task.json", display = True):
    # open json file
    with open(pth, "r") as f:
        data = json.load(f)
        landscape = data["data"]
        state = data["state"]
        goal = data["goal"]
        if display:
            print("state: ", state)
            print("goal: ", goal)
            print("landscape: ", landscape)
    return landscape, state, goal

def main():

    """ parse arguments
    """
    rpl_config = ReplayConfig()

    parser = argparse.ArgumentParser()
    parser.add_argument("--model_pth", type=str, default=rpl_config.model_pth)
    parser.add_argument("--map_size", type=int, default=rpl_config.map_size)
    parser.add_argument("--task_pth", type=str, default=rpl_config.task_pth)
    parser.add_argument("--log_pth", type=str, default=rpl_config.log_pth)
    parser.add_argument("--nn_size", type=int, default=rpl_config.nn_size)
    parser.add_argument("--nn_type", type=str, default=rpl_config.nn_type)
    parser.add_argument("--show_kf", type=str, default=rpl_config.show_kf)
    parser.add_argument("--visualization", type=str, default=rpl_config.visualization)
    parser.add_argument("--video_output", type=str, default=rpl_config.video_output)
    parser.add_argument("--life_duration", type=int, default=rpl_config.life_duration)

    args = parser.parse_args()

    rpl_config.model_pth = args.model_pth
    rpl_config.map_size = args.map_size
    rpl_config.task_pth = args.task_pth
    rpl_config.log_pth = args.log_pth
    rpl_config.nn_size = args.nn_size
    rpl_config.nn_type = args.nn_type
    rpl_config.show_kf = args.show_kf
    rpl_config.visualization = args.visualization
    rpl_config.video_output = args.video_output
    rpl_config.life_duration = args.life_duration

    nn_type = ''
    if rpl_config.nn_type == "vanilla":
        nn_type = "vanilla"
    elif rpl_config.nn_type == "gru":
        nn_type = "gru"

    def load_data_and_compute(nn_type, seq_len, redundancy, diverse_set_capacity):

        rnn_limit_rings_file_name = "./logs/rnn_limit_rings_of_best_estimation_" + nn_type + "_" + str(seq_len) + "_" + str(redundancy) + "_" + str(diverse_set_capacity) + ".npz"
        # 载入 npz 文件
        rnn_limit_rings_of_best_estimation_file = np.load(rnn_limit_rings_file_name)

        # 获取 npz 文件中的所有对象名称
        matrix_names = rnn_limit_rings_of_best_estimation_file.files

        rnn_limit_rings_of_best_estimation = []

        # 遍历对象名称，访问和操作每个矩阵对象
        for name in matrix_names:
            matrix = rnn_limit_rings_of_best_estimation_file[name]
            # 在这里进行对矩阵对象的操作
            # 例如，打印矩阵的形状
            # print(f"Matrix '{name}' shape: {matrix.shape}")
            rnn_limit_rings_of_best_estimation.append(matrix)

        # 求 rnn_limit_rings_of_best_estimation 的中心位置序列
        rnn_limit_rings_of_best_estimation_center = []
        for i in range(len(rnn_limit_rings_of_best_estimation)):
            rnn_limit_rings_of_best_estimation_center.append(np.mean(rnn_limit_rings_of_best_estimation[i], axis=(0,1)))
            # print("shape of rnn_limit_rings_of_best_estimation[i] is: ", rnn_limit_rings_of_best_estimation[i].shape)
        rnn_limit_rings_of_best_estimation_center = np.array(rnn_limit_rings_of_best_estimation_center)
        print("rnn_limit_rings_of_best_estimation_center.shape: ", rnn_limit_rings_of_best_estimation_center.shape)

        # load obs data
        file_name = "obs_data_" + nn_type + "_" + str(seq_len) + "_" + str(redundancy) + "_" + str(diverse_set_capacity) + ".npz"
        obs_file = np.load("./logs/" + file_name)
        obs_data = obs_file["obs_data"]
        diverse_set_trajectoies = obs_file["diverse_set_trajectoies"]
        diverse_set_actions = obs_file["diverse_set_actions"]

        # print("shape of obs_data is: ", obs_data.shape)

        return rnn_limit_rings_of_best_estimation_center, \
                copy.deepcopy(rnn_limit_rings_of_best_estimation)
    
    configs = [

        [nn_type, 6, 1, 100],
        [nn_type, 7, 1, 100],
        [nn_type, 8, 1, 100],
        [nn_type, 9, 1, 100],
        [nn_type, 10, 1, 100],
        [nn_type, 11, 1, 100],
        [nn_type, 12, 1, 100],
        [nn_type, 13, 1, 100],
        [nn_type, 14, 1, 100],
        [nn_type, 15, 1, 100],
        
        ]

    rnn_limit_rings_of_best_estimation_centers = []
    policy_rings_raw_data = []
    for i in range(len(configs)):
        centers, raw_data = load_data_and_compute(configs[i][0], configs[i][1], configs[i][2], configs[i][3])
        rnn_limit_rings_of_best_estimation_centers.append(centers)
        policy_rings_raw_data.append(raw_data)

    # 将 rnn_limit_rings_of_best_estimation_centers 所有元素拼接起来
    rnn_limit_rings_of_best_estimation_center_mat = np.concatenate(rnn_limit_rings_of_best_estimation_centers, axis=0)

    # 生成一个表，用于将拼接起来之后的元素位置映射回原来在 rnn_limit_rings_of_best_estimation_centers 中的位置
    rnn_limit_rings_of_best_estimation_center_mat_index_table = []
    for i in range(len(rnn_limit_rings_of_best_estimation_centers)):
        for j in range(rnn_limit_rings_of_best_estimation_centers[i].shape[0]):
            rnn_limit_rings_of_best_estimation_center_mat_index_table.append([i, j])

    print("shape of rnn_limit_rings_of_best_estimation_center_mat_index_table: ", np.array(rnn_limit_rings_of_best_estimation_center_mat_index_table).shape)

    # 对 rnn_limit_rings_of_best_estimation_center_mat 进行 PCA
    pca = PCA()
    pca.fit(rnn_limit_rings_of_best_estimation_center_mat)
    rnn_limit_rings_of_best_estimation_center_mat_pca = pca.transform(rnn_limit_rings_of_best_estimation_center_mat)

    # # 打印 pca 的 explained_variance_ratio_
    # print("pca.explained_variance_ratio_: ", pca.explained_variance_ratio_)

    # 计算每个点的方向角
    angles = np.arctan2(rnn_limit_rings_of_best_estimation_center_mat_pca[:, 1], rnn_limit_rings_of_best_estimation_center_mat_pca[:, 0])

    # 将弧度转换为角度
    angles_degrees = np.degrees(angles)

    phase_sorted_idx = np.argsort(angles_degrees)

    # 对 rnn_limit_rings_of_best_estimation_center_mat_pca 按照 angles_degrees 进行排序
    rnn_limit_rings_of_best_estimation_center_mat_pca_sorted = rnn_limit_rings_of_best_estimation_center_mat_pca[phase_sorted_idx]

    # 在 phase_sorted_idx 中随机选择一个点，然后选择这个点附近序号 [-10,+10] 范围内的点
    set_cap = 20
    rnd_idx = np.random.randint(phase_sorted_idx.shape[0])
    PR_points_chosen = phase_sorted_idx[rnd_idx-set_cap:rnd_idx+set_cap]
    print("PR_points_chosen: ", PR_points_chosen)

    """ 绘图
    """

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    for i in range(rnn_limit_rings_of_best_estimation_center_mat_pca_sorted.shape[0]):
        color = plt.cm.jet((i+1) / (rnn_limit_rings_of_best_estimation_center_mat_pca_sorted.shape[0] - 1))  # 根据序号 i 计算颜色
        ax.scatter(rnn_limit_rings_of_best_estimation_center_mat_pca_sorted[i, 0], rnn_limit_rings_of_best_estimation_center_mat_pca_sorted[i, 1],
                    rnn_limit_rings_of_best_estimation_center_mat_pca_sorted[i, 2], s=10, c=color)
        
    # 添加颜色标尺, 用于显示颜色和序号的对应关系
    cax, _ = matplotlib.colorbar.make_axes(ax)
    cbar = matplotlib.colorbar.ColorbarBase(cax, cmap=plt.cm.jet)
    cbar.set_ticks([0, 1])
    cbar.set_ticklabels([0, 360])
    cbar.set_label('degree')

    # # 用红色 scatter 绘制 rnn_limit_rings_of_best_estimation_center_mat_pca
    # ax.scatter(rnn_limit_rings_of_best_estimation_center_mat_pca[:, 0], rnn_limit_rings_of_best_estimation_center_mat_pca[:, 1],
    #             rnn_limit_rings_of_best_estimation_center_mat_pca[:, 2], s=10, c='red')
    
    # # 绘制 PR_points_chosen
    # ax.scatter(rnn_limit_rings_of_best_estimation_center_mat_pca[PR_points_chosen, 0], rnn_limit_rings_of_best_estimation_center_mat_pca[PR_points_chosen, 1],
    #             rnn_limit_rings_of_best_estimation_center_mat_pca[PR_points_chosen, 2], s=100, c='green')

    ax.view_init(elev=90, azim=0)  # 设置视角为从上方看下去
    plt.show()

            
if __name__ == "__main__":
    main()
